package com.stox.client.ui.javafx.chartingy.model.node;

import javafx.scene.layout.Region;
import javafx.scene.paint.Color;
import javafx.scene.shape.Line;

import com.stox.client.ui.javafx.chartingy.model.Rectangle;
import com.stox.client.ui.javafx.chartingy.model.plot.Data;
import com.stox.client.ui.javafx.chartingy.model.plot.PricePlot;
import com.stox.client.ui.javafx.core.util.CSS;
import com.stox.client.ui.javafx.core.util.UI;
import com.stox.shared.core.model.Bar;
import com.stox.shared.core.model.Scrip;

public class Candle extends AbstractPriceNode {

	private Line highLowLine = new Line();
	private Region region = new Region();
	
	public Candle(Data<Scrip, Bar> data) {
		super(data);
		UI.style(this, CSS.barNode, CSS.candle);
		
		getChildren().addAll(highLowLine, region);
		highLowLine.endXProperty().bind(highLowLine.startXProperty());
		updateColor();
	}
	
	@Override
	public void updateColor() {
		PricePlot plot = (PricePlot)getData().getPlot();
		Color color = null == up ? plot.getColor() : up ? plot.getUpBarColor() : plot.getDownBarColor();
		setStyle("-fx-bar-color:"+UI.web(color)+";");
	}

	@Override
	public void layoutChartChildren() {
		Data<Scrip,Bar> data = getData();
		Bar bar = (Bar)data.getExtraValue();
		
		double high = getDisplayPosition(bar.getHigh());
		double low = getDisplayPosition(bar.getLow());
		Rectangle rectangle = getRectangle();
		rectangle.setY(high);
		rectangle.setHeight(low - high);
		double width = rectangle.getWidth();
		double x = rectangle.getX() + width/2;
		
		double strokeWidth = 10 < width ? width/10 : 1;
		highLowLine.setStrokeWidth(strokeWidth);
		
		highLowLine.setStartX(x);
		highLowLine.setStartY(high);
		highLowLine.setEndY(low);
		
		double upper = Math.max(bar.getOpen(), bar.getClose());
		double lower = Math.min(bar.getOpen(), bar.getClose());
		double y = getDisplayPosition(upper);
		double height = getDisplayPosition(lower) - y;
		height = height < 1 ? 1 : height;
		width = width*(1-data.chartingView().getBarGap());
		region.resizeRelocate(x - width/2, y, width, height);
	}

}
